#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
Simplified BSD License (BSD)
Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this 
      list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 11-Nov-09 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Security.Permissions;

using Thn;
#endregion

namespace Thn.Interface.Vcl
{
    /// <summary>
    /// A Base popup editor inherit from a windows form control.
    /// </summary>
#if DEBUG 
    public
#else
    public
#endif 
    partial class PopupFormBase : Form
    {
        #region Fields
        #endregion

        #region Properties

        #region Controller
        /// <summary>
        /// Gets/Sets the controller which manages this form
        /// </summary>
        protected IPopupController mController;
        /// <summary>
        /// Gets/Sets the controller which manages this form
        /// </summary>
        [Browsable(false), DefaultValue(null)]
        public IPopupController Controller
        {
            get { return mController; }
            set { mController = value; }
        }
        #endregion

        #region Editor
        private IPopupEditor mEditor;
        /// <summary>
        /// Gets/Sets the editor this form contains
        /// </summary>
        [Browsable(false), DefaultValue(null)]
        public IPopupEditor Editor
        {
            get { return mEditor; }
            set { mEditor = value; }
        }
        #endregion

        #region Handle Escape Key
        private bool mHandleEscapeKey = true;
        /// <summary>
        /// Gets/Sets whether the popup automatically cancels when user press Escape key.
        /// <para>Default is true</para>
        /// </summary>
        [Browsable(true), DefaultValue(true), Category("Behavior"), Description("Popup automatically cancels when user press Escape key")]
        public bool HandleEscapeKey
        {
            get { return mHandleEscapeKey; }
            set { mHandleEscapeKey = value; }
        }
        #endregion

        #region Drop Shadow
        private bool mDropShadow = true;
        /// <summary>
        /// Shows a soft shadow at edge of popup form.
        /// <para>Default is true</para>
        /// </summary>
        [Browsable(true), DefaultValue(true), Category("Appearance"), Description("Shows a soft shadow at edge of popup form.")]
        public bool DropShadow
        {
            get { return mDropShadow; }
            set { mDropShadow = value; }
        }
        #endregion

        #region Draw Border
        private bool mDrawBorder = true;
        /// <summary>
        /// Show border
        /// </summary>
        [Browsable(true), DefaultValue(true), Category("Appearance"), Description("Show border")]
        public bool DrawBorder
        {
            get { return mDrawBorder; }
            set { mDrawBorder = value; }
        }
        #endregion

        #region Border Color
        private Color mBorderColor;
        /// <summary>
        /// Gets/Sets color of border
        /// </summary>
        [Browsable(true), Category("Appearance")]
        public Color BorderColor
        {
            get { return mBorderColor; }
            set { mBorderColor = value; }
        }
        #endregion

        #region Create Params
        protected override CreateParams CreateParams
        {
            [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
            get
            {
                //turn on drop-shadow mode

                CreateParams parameters = base.CreateParams;

                int CSmDROPSHADOW = 0x00020000;

                OperatingSystem system = Environment.OSVersion;
                bool DropShadowSupported = system.Platform == PlatformID.Win32NT;

                DropShadowSupported = DropShadowSupported && system.Version.CompareTo(new Version(5, 1, 0, 0)) >= 0;

                if (DropShadowSupported)
                {
                    parameters.ClassStyle = (parameters.ClassStyle | CSmDROPSHADOW);
                }

                return parameters;
            }
        }
        #endregion

        #endregion

        #region Setup
        /// <summary>
        /// This method is invoked by the controller to let this form prepare itself before this form is shown.
        /// </summary>
        public virtual void Setup(IPopupController controller, IPopupEditor editor)
        {
            mController = controller;
            mEditor = editor;

            //remove current editor if available
            this.Controls.Clear();

            if ((mController != null) && (mEditor != null))
            {
                //perform layout
                AdjustSize();
                Control con = (Control)mEditor;
                if (mDrawBorder)
                {
                    Rectangle r = ClientRectangle;
                    //r.Inflate(-1, -1);
                    con.SetBounds(r.Left, r.Top, r.Width, r.Height);
                    con.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                }
                else con.Dock = DockStyle.Fill;
                con.Parent = this;
            }
            #region Defensive tracing
            else
            {
                // control is null, do nothing.
            }
            #endregion
        }
        #endregion

        #region Adjust Size
        /// <summary>
        /// Calculate the position and size of this form based on the controller and editor
        /// </summary>
        protected virtual void AdjustSize()
        {
            int width = 0;
            int height = 0;

            //compute width & height
            if (mController.Width > 0) width = mController.Width;
            else width = mEditor.Width;
            if (mController.Height > 0) height = mController.Height;
            else height = mEditor.Height;

            //adjust layout
            this.ClientSize = new Size(width, height);
        }
        #endregion        

        #region UI Events processing

        #region Key Press
        private void PopupFormBase_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 27) //press Escaped
            {
                if ((mHandleEscapeKey) && (mController != null))
                {
                    e.Handled = true;
                    mController.Cancel();
                }
                #region Defensive tracing
                else 
                {
                    // the handle escape key flag is turn off or the controller 
                    // is not created, do nothing.
                }
                #endregion
            }
        }
        #endregion

        #endregion

        #region On Paint
        /// <summary>
        /// Paint the form and draw a neat border.
        /// </summary>
        /// <param name="e">Information about the paint event</param>
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            if (mDrawBorder)
            {
                Pen p = new Pen(mBorderColor);

                Rectangle borderRect = new Rectangle(this.ClientRectangle.Location, this.ClientRectangle.Size);
                borderRect.Width -= 1;
                borderRect.Height -= 1;
                e.Graphics.DrawRectangle(p, borderRect);

                p.Dispose();
            }
            #region Defensive tracing
            else 
            {
                // Just draw border when the flag above turn on only.
            }
            #endregion
        }
        #endregion
        
        #region Constructors
        /// <summary>
        /// Default constructor.
        /// </summary>
        public PopupFormBase() 
        {
            InitializeComponent();

            SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true);
            this.Text = string.Empty;
            this.ShowIcon = false;
        }
        #endregion
    }
}
